const dateformat = require('dateformat')
const crypto = require('crypto')

function QuickRender(req, res, next) {
  res.success = (code = 200, msg = '', result = []) => {
    if (typeof code === 'string') {
      if (typeof msg === 'object') {
        result = msg || []
      }
      msg = code
      code = 200
    } else if (typeof code === 'object') {
      result = code || []
      msg = 'success'
      code = 200
    }
    res.json({
      code: code,
      msg: msg,
      result: result,
    })
  }

  res.hasError = (code = 404, error, result = []) => {
    if (typeof code === 'object') {
      result = code
      error = 'failed'
      code = 404
    }
    if (typeof code === 'string') {
      error = code
      code = 404
    }
    res.status(code)
    res.json({
      code: code,
      msg: error,
      result: result,
    })
  }

  res.solt = (payload) => {
    if (typeof payload === 'object') {
      payload = JSON.stringify(payload)
    }
    return crypto.createHmac('sha256', payload)
      .update('Wivwiv%03qif093qj@1113')
      .digest('hex')
  }

  res.dateformat = (date) => {
    if (!date) {
      return 'N/A'
    }
    return dateformat(date, 'yyyy年mm月dd日 HH:MM:ss') || 'N/A'
  }
  next()
}


module.exports = QuickRender